/**
 * Copyright 2010-present Facebook.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.twodstar.selfie;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import com.actionbarsherlock.app.SherlockFragment;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestBatch;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.internal.Utility;
import com.facebook.model.GraphObject;
import com.facebook.widget.ProfilePictureView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * Fragment that represents the main selection screen for Scrumptious.
 */
public class Fragment_Best extends SherlockFragment 
{
	
	public static Fragment_Best m_Inst;
	private Uri photoUri = null;
    private ListView m_ListViewWorld;
    private boolean pendingAnnounce = false;
    private ProgressDialog progressDialog;
    private Pair<File, Integer> fileAndMinDimemsion;
    private static final String PERMISSION = "publish_actions";
    private static final int REAUTH_ACTIVITY_CODE = 100;        
    private List<Element_BestList> m_ListElementsWorld;

    private ListView m_ListViewCountry;
    private List<Element_BestList> m_ListElementsCountry;
    
    private ListView m_ListViewCity;
    private List<Element_BestList> m_ListElementsCity;
    
    private ListView m_ListViewFriends;
    private List<Element_BestList> m_ListElementsFriends;
    
    //private TextView m_TxtWorld;
    private TextView m_TxtCountry;
    private TextView m_TxtCity;
    //private TextView m_TxtFriend;
    private TextView m_TxtLoading;
    private LinearLayout m_FrameListViews;
    
    private final int QUERY_TYPE_WORLD = 0;
    private final int QUERY_TYPE_COUNTRY = 1;
    private final int QUERY_TYPE_CITY = 2;
    private final int QUERY_TYPE_FRIEND = 3;
    private final int QUERY_TYPE_TOTAL = QUERY_TYPE_FRIEND + 1;
    private static boolean m_IsAlreadyQueryed = false; 
    private Timer m_Timer = null;
    
    private BattleInfo m_BT_Info;    
        
    class BattleInfo
    {
    	 // player 1 
    	public String Player_ID1;
    	public String Player_ID2;
    	public String PlayerName_P1;
    	public String PlayerName_P2;
    	
    	public String 	PhotoID_P1;
    	public String 	PhotoID_P2;    
    	

     };
 
     public static void Recreated()
     {
    	 	m_Inst = null;
     }
    
    
    public static Fragment_Best Instace()
    {
    	if(m_Inst == null)
    		m_Inst = new Fragment_Best();
    		
    	return m_Inst;
    }
    
    public void Reset()
    {
    	m_IsAlreadyQueryed = false;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);    
        
    }

    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
    	PBUtility.LOG("BestFragment on create");
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.bestplayers, container, false);
       
        m_ListViewWorld = (ListView) view.findViewById(R.id.ListBestWorld);
        m_ListViewCountry = (ListView) view.findViewById(R.id.ListBestCountry);
        m_ListViewCity = (ListView) view.findViewById(R.id.ListBestCity);
        m_ListViewFriends = (ListView) view.findViewById(R.id.ListBestFriend);       
        
        //m_TxtWorld = (TextView) view.findViewById(R.id.txtWorld);
        m_TxtCountry = (TextView) view.findViewById(R.id.txtCountry);
        m_TxtCity = (TextView) view.findViewById(R.id.txtCity);
        //m_TxtFriend = (TextView) view.findViewById(R.id.txtFriends);
        m_TxtLoading = (TextView) view.findViewById(R.id.txtLoading);
        m_FrameListViews = (LinearLayout) view.findViewById(R.id.FrameListViews);
        
        if(m_FrameListViews != null)
        {	
        	m_FrameListViews.setVisibility(View.GONE);
        }
        
        return view;
    }
    
    public void GetBestListAfterGettingFrdList()
    {
    	if(m_IsAlreadyQueryed == false && m_Timer == null)
        {
		    final Handler handler = new Handler();
		    m_Timer = new Timer(false);
		    TimerTask timerTask = new TimerTask() 
		    {
		        @Override
		        public void run() {
		            handler.post(new Runnable() 
		            {
		                @Override
		                public void run() 
		                {
		                   Tick();                    		
		                }
		            });
		        }
		    };
		    m_Timer.scheduleAtFixedRate(timerTask, 0, 1000);
        }
    }
    
    private void Tick()
    {
    	//PBUtility.LOG("------------------------$$$----------------------");
    	
    	SelfieBattleApplication app = SelfieBattleApplication.Instance();
    	boolean IsAlreadyInitFrdList = app.GetIsAlreadyInitFrdUIDs();
    	
    	if(m_IsAlreadyQueryed == false && IsAlreadyInitFrdList )
        {
    		m_Timer.cancel();
        	m_Timer = null;
        	m_IsAlreadyQueryed = true;
        	
        	for(int i = 0; i < QUERY_TYPE_TOTAL; i++)
        		GetBestList(i);
        	
        	
        }
    }

   

    private class BestListAdapter extends ArrayAdapter<Element_BestList> 
    {
        private List<Element_BestList> listElements;

        public BestListAdapter(Context context, int resourceId, List<Element_BestList> listElements) 
        {
            super(context, resourceId, listElements);
            
            this.listElements = listElements;
            for (int i = 0; i < listElements.size(); i++) 
            {
                listElements.get(i).setAdapter(this);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            View view = convertView;
            if (view == null) 
            {
                LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.bestlistitem, null);
            }

            Element_BestList listElement = listElements.get(position);
            if (listElement != null) 
            {      
            	
            	ProfilePictureView ProfilePic = (ProfilePictureView) view.findViewById(R.id.profilepic);
                TextView textName = (TextView) view.findViewById(R.id.txtName);
                TextView textLevel = (TextView) view.findViewById(R.id.txtLevel);
                TextView textTitle = (TextView) view.findViewById(R.id.txtTitle);
                TextView textBattle = (TextView) view.findViewById(R.id.txtBattles);
                Button btnChallenge = (Button)view.findViewById(R.id.btnChallenge);
                
                
                listElement.SetViewElements( ProfilePic, textName, textTitle, textLevel, textBattle, btnChallenge);
            }
            return view;
        }

    }
    
    
    private void GetBestList(final int QueryType)
    {      	
    	ParseQuery<ParseUser> Q1 = ParseUser.getQuery();
    	
    	if(QueryType == QUERY_TYPE_COUNTRY)
    	{
    		if(ParseUser.getCurrentUser() == null)
        		return;
    		
    		String Country = ParseUser.getCurrentUser().getString("Country");
    		if(Country == null || Country.isEmpty())
    		{
    			if(m_TxtCountry != null)
    				m_TxtCountry.setVisibility(View.GONE);
        		return;
    		}
    		
    		Q1.whereEqualTo("Country", Country);
    		if(m_TxtCountry != null)
    			m_TxtCountry.setText( getString(R.string.BestFrom, Country) );
    	}
    	
    	else if(QueryType == QUERY_TYPE_CITY)
    	{
    		if(ParseUser.getCurrentUser() == null)
        		return;
    		
    		String City = ParseUser.getCurrentUser().getString("City");
    		if(City == null || City.isEmpty())
    		{
    			if(m_TxtCity != null)
        			m_TxtCity.setVisibility(View.GONE);
        		return;
    		}
    		
    		Q1.whereEqualTo("City", City);
    		if(m_TxtCity != null)
    			m_TxtCity.setText(getString(R.string.BestFrom, City));
    	}
    	
    	else if(QueryType == QUERY_TYPE_FRIEND)
    	{
    		SelfieBattleApplication app = SelfieBattleApplication.Instance();
    		String[] FBIDs = app.GetAppFrdList();
    		if(FBIDs == null)
    			return;
    		Q1.whereContainedIn("FBID", Arrays.asList(FBIDs));
    	}
    	
    	Q1.orderByDescending("BattleWin");
    	Q1.setLimit(5);    			
    	
    	
    	
    	Q1.findInBackground(new FindCallback<ParseUser>() 
    	{
    	  
    	  public void done(List<ParseUser> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)    		  
    		  {
    			  	if(m_TxtLoading != null)
    			  		m_TxtLoading.setVisibility(View.GONE);
    			  	
    			  	 if(m_FrameListViews != null)
    			        {	
    			        	m_FrameListViews.setVisibility(View.VISIBLE);
    			        }
    		  	    		  
    			  	if(QueryType == QUERY_TYPE_WORLD)	  	        	
    				  m_ListElementsWorld = new ArrayList<Element_BestList>();
    			  	
	  	        	else if(QueryType == QUERY_TYPE_COUNTRY)	  	        	
	  	        		m_ListElementsCountry = new ArrayList<Element_BestList>();
	  	        	
	  	        	else if(QueryType == QUERY_TYPE_CITY)	  	        	
	  	        		m_ListElementsCity = new ArrayList<Element_BestList>();
	  	        	
	  	        	else if(QueryType == QUERY_TYPE_FRIEND)	  	        	
	  	        		m_ListElementsFriends = new ArrayList<Element_BestList>();
	  	        	
	    	          	        
	    	        
	    	        //  Add Player's Battle First
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseUser Obj = results.get(i);	    	
	    	        	
	    	        	if(QueryType == QUERY_TYPE_WORLD)	  	        	
	    	        		AddToListElements(Obj, m_ListElementsWorld, true);
	      			  	
	  	  	        	else if(QueryType == QUERY_TYPE_COUNTRY)	  	        	
	  	  	        		AddToListElements(Obj, m_ListElementsCountry, true);
	  	  	        	
	  	  	        	else if(QueryType == QUERY_TYPE_CITY)	  	        	
	  	  	        		AddToListElements(Obj, m_ListElementsCity, true);
	  	  	        	
	  	  	        	else if(QueryType == QUERY_TYPE_FRIEND)	  	        	
	  	  	        	AddToListElements(Obj, m_ListElementsFriends, false);
	    	        	
	    	        	
	    	        }	   	        
	    	        	        
	
	    	        if(getActivity() != null )
	    	        {
	    	        	if(QueryType == QUERY_TYPE_WORLD)
	    	        	{
	    	        		m_ListViewWorld.setAdapter(new BestListAdapter(getActivity(), R.id.ListBestWorld, m_ListElementsWorld));	    	        		
	    	        	}
	    	        	else if(QueryType == QUERY_TYPE_COUNTRY)
	    	        	{
	    	        		m_ListViewCountry.setAdapter(new BestListAdapter(getActivity(), R.id.ListBestCountry, m_ListElementsCountry));	    	        		
	    	        	}
	    	        	else if(QueryType == QUERY_TYPE_CITY)
	    	        	{
	    	        		m_ListViewCity.setAdapter(new BestListAdapter(getActivity(), R.id.ListBestCity, m_ListElementsCity));
	    	        	}
	    	        	else if(QueryType == QUERY_TYPE_FRIEND)
	    	        	{
	    	        		m_ListViewFriends.setAdapter(new BestListAdapter(getActivity(), R.id.ListBestFriend, m_ListElementsFriends));
	    	        	}
	    	        }
	    	        
	    	       
    		  }
    	  }
    	});
    	
    }
    
    private void AddToListElements(ParseUser Pobj,List<Element_BestList> LE, boolean ToHideButtonChallenge )
    {
    	SelfieBattleApplication app = SelfieBattleApplication.Instance();
    	String Title = app.GetPlayerTitle(Pobj);
    	int BattleWin = Pobj.getInt("BattleWin");
    	int Level = SelfieBattleApplication.Instance().CalculateLevel(BattleWin );
    	
    	LE.add( new Element_BestList(
    								this,
    								getActivity(), 
    								Pobj.getString("FBID"), 
    								Pobj.getUsername(), 
    								Title, 
    								Level, 
    								Pobj.getInt("TotalBattle"), 
    								BattleWin,
    								ToHideButtonChallenge
    								)
    			);    	
		
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
    	// TODO Auto-generated method stub
    	super.onActivityResult(requestCode, resultCode, data);
    	PBUtility.LOG(" request code " + requestCode);
    	
    	Uri tempUri = Element_BestList.GetResultURI();
        if (tempUri != null) 
        {
            photoUri = tempUri;
        } 
        else if (data != null) 
        {
            photoUri = data.getData();
        }

        if(photoUri != null)
        	handleAnnounce();
    }
    
    public void onSessionStateChange(final Session session, SessionState state, Exception exception) 
    {
        if (session != null && session.isOpened()) 
        {
            if (state.equals(SessionState.OPENED_TOKEN_UPDATED)) 
            {
                tokenUpdated();
            } 
           
        } 
        else 
        {
            
        }
    }
    
    private void tokenUpdated() 
    {
        if (pendingAnnounce) 
        {
            UploadPhotoToFB();
        }
    }
    
    private void handleAnnounce() 
    {
        pendingAnnounce = false;
        Session session = ParseFacebookUtils.getSession();        
        
        if (session != null && session.isOpened())
        {
        	// Show a progress dialog because sometimes the requests can take a while.
            progressDialog = ProgressDialog.show(getActivity(), "",  getActivity().getResources().getString(R.string.progress_dialog_text), true);
	        
 	        // upload photo
            fileAndMinDimemsion = getImageFileAndMinDimension();
	        if(fileAndMinDimemsion == null)
	        {
	        	//ShowCannotCreateBattle("This photo can't be used!");
	        	return;
	        }
	        
	        String PlayerID2 =  "";
	        
	        if(Element_BestList.m_ToAttackObject != null)
	        {
	        	PlayerID2 = Element_BestList.m_ToAttackObject.GetFBID();
	        }
	        
	        String fqlQuery = "SELECT  object_id FROM photo WHERE aid in (SELECT aid FROM album WHERE owner = '" + PlayerID2 + "' AND type = 'profile') LIMIT 0,1";
	        Bundle params = new Bundle();
	        params.putString("q", fqlQuery);

	        Request request = new Request(session, 
	            "/fql", 
	            params, 
	            HttpMethod.GET, 
	            new Request.Callback()
	        { 
	                public void onCompleted(Response response) 
	                {
	                	 GraphObject graphObject = response.getGraphObject();	                	
	                	
	                	 if (graphObject != null) 
	                	 {
	                		 if(m_BT_Info == null)
	                         {
	                        	m_BT_Info = new BattleInfo();
	                        	m_BT_Info.PhotoID_P1 = "";
	                        	m_BT_Info.PhotoID_P2 = "";
	                        	m_BT_Info.Player_ID1 = "";
	                        	m_BT_Info.PlayerName_P1 = "";
	                        	m_BT_Info.PlayerName_P2 = "";
	                         }
                		 
	                         JSONObject jsonObject = graphObject.getInnerJSONObject();
	                         
	                         try 
	                         {
	                             JSONArray array = jsonObject.getJSONArray("data");
	                             for (int i = 0; i < array.length(); i++) 
	                             {
	                                 JSONObject object = (JSONObject) array.get(i);
	                                 m_BT_Info.PhotoID_P2 = object.get("object_id").toString();                                
	                             }
	                        } 
	                        catch (JSONException e) 
	                        {
	                        	e.printStackTrace();
	                        	if (progressDialog != null) 
                                {
                                    progressDialog.dismiss();
                                    progressDialog = null;
                                }
	                        }	                         
	                         
	                       
	                        // player 1
	                        
	                        if(Element_BestList.m_ToAttackObject != null)
	                        {
	                        	m_BT_Info.Player_ID2 = Element_BestList.m_ToAttackObject.GetFBID();
	                        	m_BT_Info.PlayerName_P2 =    Element_BestList.m_ToAttackObject.GetName();
	                        }
		        	        
	                        m_BT_Info.Player_ID1 = SelfieBattleApplication.Instance().GetFBID();
		        	        m_BT_Info.PlayerName_P1 = SelfieBattleApplication.Instance().GetName();
		        	          
		                	
		         	        // upload photo
		         	        UploadPhotoToFB();
	                        
	                        //DataManager.UpdateWinnerID("UQcyr65MpK", "549483876" , "549483876", "100004546325654");
	                        PBUtility.LOG("date: " + System.currentTimeMillis()); 
	                        
	                	 }
	                	 else
	                	 {
	                		 if (progressDialog != null) 
                             {
                                 progressDialog.dismiss();
                                 progressDialog = null;
                             }
	                	 }
	            }
	        });
	        
	        
	        Request.executeBatchAsync(request);   
	       
        }
    }
    
    private void UploadPhotoToFB() 
    {
    	Session session = ParseFacebookUtils.getSession();

        List<String> permissions = session.getPermissions();
        if (!permissions.contains(PERMISSION)) 
        {
            pendingAnnounce = true;
            if(progressDialog != null )
            {
            	progressDialog.dismiss();
            	progressDialog = null;
            }
            
            if(getActivity() != null)
            {
            	((MainActivity)getActivity()).requestPublishPermissions(session,REAUTH_ACTIVITY_CODE);
            }
           
            return;
        }
        
       
        
        // Run this in a background thread so we can process the list of responses and extract errors.
        AsyncTask<Void, Void, List<Response>> task = new AsyncTask<Void, Void, List<Response>>() 
        {
        	 @Override
        	 public void onPostExecute(List<Response> citations) 
        	 {
        		 if (fileAndMinDimemsion != null) 
        			 GetPhotoAlbumnViewURLAndLikeCount( m_BT_Info.PhotoID_P1 ,  m_BT_Info.PhotoID_P2 );
        	 }
        	 

            @Override
            protected List<Response> doInBackground(Void... voids) 
            {
                

                RequestBatch requestBatch = new RequestBatch();

                //String photoStagingUri = null;

                if (photoUri != null) 
                {
                    try 
                    {
                        
                        
                        if (fileAndMinDimemsion != null) 
                        {
                        	// create a response callback for uploading photo
                        	Request.Callback imageCallback = new Request.Callback() 
                        	{
                        		
                                @Override
                                public void onCompleted(Response response) 
                                {
                                	                              	
                                    // Log any response error
                                    FacebookRequestError error = response.getError();
                                    if (error != null) 
                                    {                                      
                                    	PBUtility.LOG(error.getErrorMessage());
                                    	ShowCannotUploadPhoto();                                    	
                                    }
                                    else
                                    {
                                    	PBUtility.LOG(response.toString());  
                                    	
                                    	GraphObject graphObject = response.getGraphObject();
                                    	if (graphObject != null) 
               	                	 	{
	                                    	JSONObject jsonObject = graphObject.getInnerJSONObject();
	                                    	
	                                    	 try 
	            	                         {
	            	                            
	                                    		 PBUtility.LOG("id = "+ jsonObject.get("id"));	            	                               
	                                    		 m_BT_Info.PhotoID_P1 = jsonObject.get("id").toString();   
	            	                             
	            	                        } 
	            	                        catch (JSONException e) 
	            	                        {
	            	                        	e.printStackTrace();
	            	                        }	  	                        
	                                    	           		         	                        		         	       
	            	                       
               	                	 	}
            		         	        
                                    }
                                }
                            };
                        	
                            Request photoUploadRequest = Request.newUploadPhotoRequest(Session.getActiveSession(),
                                            											fileAndMinDimemsion.first, imageCallback);
                            Bundle params = photoUploadRequest.getParameters();
                            params.putString("message", "#Selfie Battle via #SelfieBattle http://goo.gl/NaDjRj");
                            
                                                       
                            photoUploadRequest.setBatchEntryName("photoUpload");
                            requestBatch.add(photoUploadRequest);                            
                          
                           
                        }
                    } 
                    catch (FileNotFoundException e) 
                    {
                    	ShowCannotUploadPhoto();
                    	return null;
                    }
                }      
              
                if (fileAndMinDimemsion == null) 
                {
                	ShowCannotUploadPhoto();
                	requestBatch.add(new Request()) ;
                }
             
                return requestBatch.executeAndWait();
            }
            

           
        };

        task.execute();
    }
    
    
    private void GetPhotoAlbumnViewURLAndLikeCount(String ID1, String ID2)
    {    	
   
    	Session session = Session.getActiveSession();
    	
    	 if (session != null && session.isOpened())
         {}
    	 else
    	 {
    		 return;
    	 }
    	 
    	
    	
    	 String fqlQuery = "SELECT src, like_info FROM photo WHERE object_id = '" + ID1 + "' OR object_id = '" + ID2 + "' ";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);

        Request request = new Request(session, 
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
                public void onCompleted(Response response) 
                {
                	
                	 GraphObject graphObject = response.getGraphObject();
                	 String AlbumnViewURL1 = "";
	               	 String AlbumnViewURL2 = "";
	               	 int LIKE_COUNT_P2 = 0;	       
	               	 
	               	 if (graphObject != null) 
	               	 {
	                        JSONObject jsonObject = graphObject.getInnerJSONObject();
	                        
	                        try 
	                        {
	                            JSONArray array = jsonObject.getJSONArray("data");
	                            for (int i = 0; i < array.length(); i++) 
	                            {
	                            	JSONObject object = (JSONObject) array.get(i);
	                                PBUtility.LOG("url = "+ object.get("src"));
	                                
	                                if(i == 0)
	                                {
	                                	AlbumnViewURL1 = object.get("src").toString();
	                                }
	                                else if( i == 1)
	                                {
	                                	AlbumnViewURL2 = object.get("src").toString();
	                                	
	                                	JSONObject jsonObjectLIKE = object.getJSONObject("like_info");
	                                	LIKE_COUNT_P2 = jsonObjectLIKE.getInt("like_count");
	                                }
	                                
	                                PBUtility.LOG(AlbumnViewURL1);
	                                PBUtility.LOG(AlbumnViewURL2);
	                                PBUtility.LOG("LIKE COUNT: " + LIKE_COUNT_P2);                            
	                                
	                               	 
	                            }
	                       } 
	                       catch (JSONException e) 
	                       {
	                    	   e.printStackTrace();
	                    	   if (progressDialog != null) 
                               {
                                   progressDialog.dismiss();
                                   progressDialog = null;
                               }
	                       }
	                        
	                        
	                       Element_BestList BU = Element_BestList.m_ToAttackObject;	        
	                       if(BU != null )
	                       {
	                    	   DataManager.SaveBattle( m_BT_Info.Player_ID1 , m_BT_Info.Player_ID2 , m_BT_Info.PhotoID_P1 , m_BT_Info.PhotoID_P2 ,
    	        						LIKE_COUNT_P2, AlbumnViewURL1, AlbumnViewURL2,
    	        						m_BT_Info.PlayerName_P1 , m_BT_Info.PlayerName_P2 );
	                    	   
	                    	   
	                    	   
	                    	   photoUri = null;
			         	       
			         	        
			         	       if (progressDialog != null) 
	                           {
	                               progressDialog.dismiss();
	                               progressDialog = null;
	                           }
			         	       
			         	      ShowFragmentBattles();
	                       }
		         	        
		         	       photoUri = null;		         	      
		         	        
		         	       if (progressDialog != null) 
                           {
                               progressDialog.dismiss();
                               progressDialog = null;
                           } 
		         	       
	                }
	               	else
	               	{
	               		if (progressDialog != null) 
                        {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
	               	}
                }
                
        });
        
        Request.executeBatchAsync(request);
    }
    
    private void ShowFragmentBattles()
 	{
 		MainActivity Ac  = (MainActivity)getActivity();
 		if(Ac != null)
 		{
 			Ac.showFragment( MainActivity.BATTLES);
 		}
 	}
    
    private void ShowCannotUploadPhoto()
    {
    	if (progressDialog != null) 
        {
            progressDialog.dismiss();
            progressDialog = null;
            
        }
    	
    	String text = getString(R.string.check_internet);
        Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
        toast.show();
    }
    
    private Pair<File, Integer> getImageFileAndMinDimension() 
    {
        File photoFile = null;
        if(photoUri == null)
        	return null;
        
        String photoUriString = photoUri.toString();
        if (photoUriString.startsWith("file://")) 
        {
            photoFile = new File(photoUri.getPath());
        } 
        else if (photoUriString.startsWith("content://")) 
        {
            String [] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor =  getActivity().getContentResolver().query(photoUri, filePath, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePath[0]);
                String filename = cursor.getString(columnIndex);
                cursor.close();

                photoFile = new File(filename);
            }
        }

        if (photoFile != null) 
        {
            InputStream is = null;
            try 
            {
                is = new FileInputStream(photoFile);

                // We only want to get the bounds of the image, rather than load the whole thing.
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(is, null, options);

                return new Pair<File, Integer>(photoFile, Math.min(options.outWidth, options.outHeight));
            } 
            catch (Exception e) 
            {
                return null;
            } 
            finally {
                Utility.closeQuietly(is);
            }
        }
        return null;
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);
        //outState.put
    }
    
    //@Override
   // public void onDestroy() 
   // {
    	// TODO Auto-generated method stub
    	//super.onDestroy();
   // }
    
}
